package cn.valo.org.service.impl;

import cn.valo.basic.query.BaseQuery;
import cn.valo.basic.util.BaiduAuditUtils;
import cn.valo.basic.util.PageList;
import cn.valo.basic.exception.BusinessException;
import cn.valo.org.domain.Employee;
import cn.valo.org.domain.Shop;
import cn.valo.org.domain.ShopVo;
import cn.valo.org.mapper.EmployeeMapper;
import cn.valo.org.mapper.ShopAuditLogMapper;
import cn.valo.org.mapper.ShopMapper;
import cn.valo.org.service.IShopService;
import cn.valo.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author valo
 * @since 2022-06-12
 */
@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeServiceImpl employeeServiceImpl;
    @Autowired
    private ShopAuditLogMapper shopAuditLogMapper;
    @Override
    public void settlement(Shop shop) throws BusinessException {
        if(shop.getName()==null){throw new BusinessException("店铺名不能为空");}
        //百度ai审核
        if(!BaiduAuditUtils.TextCensor(shop.getName())){throw new BusinessException("店铺名不合法，请重新输入！");}
        if(shopMapper.queryByName(shop.getName())!=null){throw new BusinessException("店铺已被注册");}
        Employee emp=employeeServiceImpl.queryById(shop.getAdminId());
        if(emp!=null){
           if(emp.getShop_id()!=null){throw new BusinessException("管理员已注册店铺!");}
           shop.setAdminId(emp.getId());
           shopMapper.insert(shop);
        }
        if(emp==null){
            Employee employee = shop.getAdmin();
        employeeServiceImpl.save(employee);
        shopMapper.insert(shop);
        employee.setShop_id(shop.getId());
        employeeServiceImpl.update(employee);
        shop.setAdminId(employee.getId());
        shopMapper.update(shop);
        }
    }

    @Override
    public List<ShopVo> countByState() {
        return shopMapper.countByState();
    }

    @Override
    public PageList<Shop> queryPage(BaseQuery tQuery) {
        PageList<Shop> shopPageList = super.queryPage(tQuery);
        shopPageList.getRows().forEach(shop->{
            if(shop.getState()!=0)
                shop.setLog(shopAuditLogMapper.queryByShopId(shop.getId()));
        });
        return shopPageList;
    }
}
